package com.edu.learning.concurrent.sample.mode3;

import com.google.common.util.concurrent.ThreadFactoryBuilder;

import java.util.concurrent.*;

/**
 * @author ll
 * @Date 2017/10/25 14:53
 */
public class ExecutorDemo {

    public static void main(String[] args) {

        ExecutorService singleThreadPool = Executors.newSingleThreadExecutor();//LinkedBlockingQueue
        ExecutorService fixedThreadPool = Executors.newFixedThreadPool(5);//LinkedBlockingQueue
        ExecutorService cachedThreadPool = Executors.newCachedThreadPool();//SynchronousQueue
        ScheduledExecutorService singleThreadScheduledPool = Executors.newSingleThreadScheduledExecutor();//DelayedWorkQueue
        ScheduledExecutorService scheduledPool = Executors.newScheduledThreadPool(5);//DelayedWorkQueue
        ExecutorService workStealingPool = Executors.newWorkStealingPool(2);//ForkJoinPool.defaultForkJoinWorkerThreadFactory

        ThreadFactory threadFactory =
                new ThreadFactoryBuilder().setDaemon(true).setNameFormat("ExecutorDemo-%d").build();
        ExecutorService executorService = new ThreadPoolExecutor(
                32,
                32,
                0L,
                TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<>(1024),
                threadFactory,
                new ThreadPoolExecutor.CallerRunsPolicy());

        executorService.execute(new TestTask("task1"));
        executorService.execute(new TestTask("task2"));
        executorService.execute(new TestTask("task3"));
        executorService.shutdown();
    }

    static class TestTask implements Runnable {
        private final String name;

        public TestTask(String name) {
            this.name = name;
        }

        @Override
        public void run() {
            try {
                for (int i= 0; i < 5; i ++) {
                    TimeUnit.SECONDS.sleep(1);
                    System.out.println(name + "-[" + i + "]");
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
